package nio.nio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zengjian
 * @create 2018-05-27 9:52
 * @since 1.0.0
 */

public class NIO2Server implements Runnable {

    public static void main(String[] args) throws IOException {
        new Thread(new NIO2Server()).start();


    }

    //private static String hostname = "127.0.0.1";
    private static int port = 8080;

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stoped = false;

    public NIO2Server() throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", port), 1024);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("qidoong");
    }

    @Override
    public void run() {
        while (!stoped) {
            try {
                selector.select(1000);
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isValid()) {
                        if (key.isAcceptable()) {
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            try {
                                SocketChannel socketChannel = serverSocketChannel.accept();
                                socketChannel.configureBlocking(false);
                                socketChannel.register(selector, SelectionKey.OP_READ);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        if (key.isReadable()) {
                            SocketChannel socketChannel = (SocketChannel) key.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            int read = 0;
                            try {
                                read = socketChannel.read(byteBuffer);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (read > 0) {
                                byte[] bytes = new byte[byteBuffer.remaining()];
                                byteBuffer.flip();
                                byteBuffer.get(bytes);
                                try {
                                    System.out.println("接收到请求消息:" + new String(bytes, "utf-8"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                try {
                                    socketChannel.write(byteBuffer);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } else if (read == 0) {

                            } else {

                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        this.stoped = true;
    }
}
